package org.zhouhe.modules.article.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.stereotype.Service;
import org.zhouhe.base.BaseService;
import org.zhouhe.page.PageUtil;
import org.zhouhe.vo.Article;
import org.zhouhe.vo.ArticleArticleType;
import org.zhouhe.vo.ArticleIndustry;
import org.zhouhe.vo.ArticleReco;
import org.zhouhe.vo.ArticleReport;
import org.zhouhe.vo.ArticleType;

@Service
@SuppressWarnings("unchecked")
public class ArticleService extends BaseService {
	public Article getArticleDetail(Article article) {
		return (Article) dao.get(Article.class, article.getArticleId());
	}

	public PageUtil getArticleList(PageUtil pageUtil, Article article, Integer industryId, Integer typeId) {
		if (pageUtil == null) {
			pageUtil = new PageUtil();
		}
		List<Object> paramList = new ArrayList<Object>();
		String select = "select distinct a ";
		StringBuilder from = new StringBuilder();
		from.append(" from Article a ");
		from.append(" left join a.articleIndustries i ");
		from.append(" left join a.articleArticleTypes t ");
		from.append(" where a.status=1 ");
		if (article == null) {
			article = new Article();
		}
		// 文章类型：
		if (typeId != null && typeId > 0) {
			from.append(" and t.articleType.idPath like ?");
			paramList.add("%|"+ typeId +"|%");
		}
		// 所属行业：
		if (industryId != null && industryId > 0) {
			//from.append(" and industry.idPath like ?");
			from.append(" and i.industry.idPath like ? ");
			paramList.add("%|"+ industryId + "|%");
		}
		// 关键字：
		if (article.getTitle() != null && !"".equals(article.getTitle().trim())) {
			from.append(" and (a.title like ? or a.summary like ?) ");
			paramList.add("%" + article.getTitle() + "%");
			paramList.add("%" + article.getTitle() + "%");
		}
		//有缩微图
		if("required".equalsIgnoreCase(article.getImgName())){
			from.append(" and (a.imgName is not null and length(trim(a.imgName))>0  ) ");
		}
		from.append(" order by a.createTime desc, a.articleId desc");
		pageUtil.setHQL(select, from.toString(), paramList);
		return dao.findByPage(pageUtil);
	}

	public List<ArticleType> getArticleTypeTreeData() {
		return dao.find("from ArticleType where articleType is null and status=1");
	}
	public ArticleType getArticleType(Integer typeId){
		return (ArticleType) dao.get(ArticleType.class, typeId);
	}

	public List<Article> getArticleByType(Integer typeId, Integer industryId, int count) {
		List<Article> articleList = null;
//		ArticleType type = (ArticleType) dao.get(ArticleType.class, typeId);
//		String hql = "from Article where articleType.idPath like :idPath and status = 1 order by createTime desc, articleId desc";
		Map<String, Object> map = new HashMap<String, Object>();
		StringBuilder hql = new StringBuilder();
		hql.append(" select distinct a ");
		hql.append(" from Article a ");
		hql.append(" left join a.articleArticleTypes t   ");
		hql.append(" left join a.articleIndustries i ");
		hql.append(" where a.status = 1 ");
		if(typeId != null){
			hql.append("    and t.articleType.idPath like :typeIdPath ");
			map.put("typeIdPath", "%|"+ typeId +"|%");
		}
		if(industryId != null){
			hql.append("    and i.industry.idPath like :industryIdPath ");
			map.put("industryIdPath", "%|"+ industryId +"|%");
		}
		hql.append(" order by a.createTime desc, a.articleId desc ");
		Query q = dao.getSessionFactory().getCurrentSession().createQuery(hql.toString());
		q.setMaxResults(count);
		q.setProperties(map);
//		if(typeId != null){
//			q.setParameter("typeIdPath", "%|"+ typeId +"|%");
//		}
//		if(industryId != null){
//			q.setParameter("industryIdPath", "%|"+ industryId +"|%");
//		}
		articleList = (List<Article>) q.list();
		return articleList;
	}
	public List<Article> getArticleRecommended(Integer typeId, Integer count){
//		String hql = "from Article where status=1 and recommended=1 and articleType.articleTypeId=:typeId order by createTime DESC, articleId DESC";
		String hql = "select distinct a from Article a left join a.articleArticleTypes t where a.status=1 and a.recommended=1 and t.articleType.articleTypeId=:typeId order by a.createTime DESC, a.articleId DESC";
		Query q = dao.getSessionFactory().getCurrentSession().createQuery(hql);
		q.setInteger("typeId", typeId);
		q.setMaxResults(count);
		return q.list();
	}
	public void save(Article article) {
		for(ArticleIndustry inds:article.getArticleIndustries()){
			inds.setArticle(article);
		}
		for(ArticleArticleType at :article.getArticleArticleTypes()){
			at.setArticle(article);
		}
		for(ArticleReco reco : article.getArticleRecos()){
			if(reco != null && reco.getIndustry() != null && reco.getIndustry().getIndustryId() != null){
				reco.setArticle(article);
				if(new Integer(1).equals(reco.getFirstPosition())){
					dao.executeUpdate("update ArticleReco set firstPosition=0 where firstPosition=1 and industry.industryId="+ reco.getIndustry().getIndustryId() +"");
				}
			}
		}
		for(ArticleReport ar : article.getArticleReports()){
			ar.setArticle(article);
		}
		article.setStatus(1);
		article.setCreateTime(new Timestamp(new Date().getTime()));
		article.setUpdateTime(new Timestamp(new Date().getTime()));
		dao.save(article);
		if(new Integer(1).equals(article.getFirstPosition())){
			dao.executeUpdate("update Article set firstPosition=0 where articleId !="+ article.getArticleId());
		}
	}

	public void update(Article article) {
		dao.executeUpdate("delete from ArticleIndustry where article.articleId="+ article.getArticleId());
		dao.executeUpdate("delete from ArticleArticleType where article.articleId="+ article.getArticleId());
		dao.executeUpdate("delete from ArticleReco where article.articleId="+ article.getArticleId());
		dao.executeUpdate("delete from ArticleReport where article.articleId="+ article.getArticleId());
		Article articleBean = (Article) dao.get(Article.class, article.getArticleId());
		articleBean.setContent(article.getContent());
		articleBean.setSummary(article.getSummary());
		articleBean.setKeywords(article.getKeywords());
//		articleBean.setIndustry(article.getIndustry());
		articleBean.setQuoteFrom(article.getQuoteFrom());
		articleBean.setTitle(article.getTitle());
		articleBean.setImgName(article.getImgName());
		articleBean.setDisplayTime(article.getDisplayTime());
		articleBean.setUpdateTime(new Timestamp(new Date().getTime()));
		articleBean.setRecoIndex(article.getRecoIndex());
		articleBean.setFirstPosition(article.getFirstPosition());
		articleBean.setArticleIndustries(article.getArticleIndustries());
		for(ArticleIndustry inds:articleBean.getArticleIndustries()){
			inds.setArticle(articleBean);
		}
		articleBean.setArticleArticleTypes(article.getArticleArticleTypes());
		for(ArticleArticleType at :articleBean.getArticleArticleTypes()){
			at.setArticle(articleBean);
		}
		articleBean.setArticleRecos(article.getArticleRecos());
		for(ArticleReco reco : articleBean.getArticleRecos()){
			if(reco != null && reco.getIndustry() != null && reco.getIndustry().getIndustryId() != null){
				reco.setArticle(article);
				if(new Integer(1).equals(reco.getFirstPosition())){
					dao.executeUpdate("update ArticleReco set firstPosition=0 where firstPosition=1 and industry.industryId="+ reco.getIndustry().getIndustryId() +" and article.articleId != "+ article.getArticleId());
				}
			}
		}
		articleBean.setArticleReports(article.getArticleReports());
		for(ArticleReport ar : article.getArticleReports()){
			ar.setArticle(article);
		}
		dao.update(articleBean);
		if(new Integer(1).equals(articleBean.getFirstPosition())){
			dao.executeUpdate("update Article set firstPosition=0 where articleId !="+ articleBean.getArticleId());
		}
	}

	public void delete(Article article) {
		dao.delete(article);
	}
	public List<Article> getRecommendIndex(Integer typeId, Integer count){
		StringBuilder hql = new StringBuilder();
		hql.append("select distinct a from Article a ");
		hql.append(" left join a.articleArticleTypes aat ");
		hql.append(" where a.status=1 and a.recoIndex=1 ");
		if(typeId != null){
			hql.append(" and aat.articleType.idPath like '%|"+ typeId +"|%' ");
		}
		hql.append(" order by a.firstPosition DESC, a.articleId ASC");
		Query q = dao.getSessionFactory().getCurrentSession().createQuery(hql.toString());
		if(count != null){
			q.setMaxResults(count);
		}
		return q.list();
	}
	public List<Article> getRecommendByIndustry1(Integer typeId, Integer industryId, Integer count){
		StringBuilder hql = new StringBuilder();
		hql.append("select distinct a from Article a ");
		hql.append(" left join a.articleArticleTypes aat ");
		hql.append(" left join a.articleIndustries ai ");
		hql.append(" left join a.articleRecos ar ");
		hql.append(" where a.status=1 ");
		if(typeId != null){
			hql.append(" and aat.articleType.idPath like '%|"+ typeId +"|%' ");
		}
		if(industryId != null){
			hql.append(" and ai.industry.idPath like '%|"+ industryId +"|%' ");
		}
		hql.append(" and ar.industry.industryId="+ industryId);
		hql.append(" order by ar.firstPosition DESC ");
		Query q = dao.getSessionFactory().getCurrentSession().createQuery(hql.toString());
		
		if(count != null){
			q.setMaxResults(count);
		}
		return q.list();
	}
	public List<Article> getRecommendByIndustry2(Integer typeId, Integer industryId, Integer count){
		List<Article> returnList = new ArrayList<Article>();
		List<Article> lst = getRecommendByIndustry1(typeId, industryId, 1);//查询被推荐的文章
		if(lst.size()>0){
			returnList.add(lst.get(0));
			count--;
		}
		StringBuilder hql = new StringBuilder();
		hql.append("select distinct a from Article a ");
		hql.append(" left join a.articleArticleTypes aat ");
		hql.append(" left join a.articleIndustries ai ");
		hql.append(" where a.status=1 ");
		if(typeId != null){
			hql.append(" and aat.articleType.idPath like '%|"+ typeId +"|%' ");
		}
		if(industryId != null){
			hql.append(" and ai.industry.idPath like '%|"+ industryId +"|%' ");
		}
		Query q = dao.getSessionFactory().getCurrentSession().createQuery(hql.toString());
		
		if(count != null){
			q.setMaxResults(count);
		}
		returnList.addAll(q.list());
		return returnList;
	}
}
